using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class PlayerController : MonoBehaviour
{
    private static PlayerController instance;

    public static PlayerController Instance => instance;

    /// <summary>
    /// 是否通过关卡
    /// </summary>
    public bool IsPassLevel { get; private set; }

    /// <summary>
    /// 是否完成条件
    /// </summary>
    public bool IsFinishCondition
    {
        get => hasGetTargetCnt >= LevelManager.Instance.LevelTargetCnt;
    }

    /// <summary>
    /// 每秒移动距离
    /// </summary>
    [SerializeField]
    private float distancePerSconed = 15;

    /// <summary>
    /// 运动Ease
    /// </summary>
    [SerializeField]
    private Ease ease = Ease.Linear;

    /// <summary>
    /// 当前移动方向  None表示静止
    /// </summary>
    private EDirection moveDirection = EDirection.None;

    /// <summary>
    /// 坐标
    /// </summary>
    private Vector2 playerPos;

    /// <summary>
    /// 目的地
    /// </summary>
    private Vector2 destination;

    /// <summary>
    /// 触发移动
    /// </summary>
    private bool triggerMove;

    /// <summary>
    /// 已获得的条件数量
    /// </summary>
    private int hasGetTargetCnt;

    /// <summary>
    /// 触摸开始位置
    /// </summary>
    private Vector2 touchBeginPosition;

    /// <summary>
    /// 触摸结束位置
    /// </summary>
    private Vector2 touchEndPosition;

    private void Awake()
    {
        if (instance != null)
            Destroy(instance.gameObject);
        instance = this;
        
    }

    private void Update()
    {
        // transform.localPosition = Vector3.MoveTowards(transform.localPosition, new Vector3(100, 1, 0f),
        //     temp * Time.deltaTime);
        // return;
        if (triggerMove)
        {
            Move();
        }

        if (moveDirection != EDirection.None || IsPassLevel) //只有当球没有前进方向时(静止)才可以输入移动操作
            return;

        if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow))
        {
            moveDirection = EDirection.Right;
            triggerMove = true;
        }
        else if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow))
        {
            moveDirection = EDirection.Left;
            triggerMove = true;
        }
        else if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow))
        {
            moveDirection = EDirection.Up;
            triggerMove = true;
        }
        else if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow))
        {
            moveDirection = EDirection.Down;
            triggerMove = true;
        }

        if (Input.touchCount > 0)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                touchBeginPosition = Input.GetTouch(0).position;
            }
            else if (Input.GetTouch(0).phase == TouchPhase.Ended)
            {
                touchEndPosition = Input.GetTouch(0).position;

                Vector2 offset = touchEndPosition - touchBeginPosition;
                if (Mathf.Abs(offset.x) > Mathf.Abs(offset.y)) //x方向变化大于y方向变化
                {
                    if (offset.x < 0)
                    {
                        triggerMove = true;
                        moveDirection = EDirection.Left;
                    }
                    else if (offset.x > 0)
                    {
                        moveDirection = EDirection.Right;
                        triggerMove = true;
                    }
                }
                else
                {
                    if (offset.y < 0)
                    {
                        moveDirection = EDirection.Down;
                        triggerMove = true;
                    }
                    else if (offset.y > 0)
                    {
                        moveDirection = EDirection.Up;
                        triggerMove = true;
                    }
                }
            }
        }
    }

    private void Move()
    {
        if (moveDirection == EDirection.None)
            return;
        triggerMove = false;
        destination = LevelManager.Instance.GetDestination(playerPos, moveDirection);
        if (destination == playerPos)
        {
            moveDirection = EDirection.None;
            return;
        }

        transform.DOLocalMove(destination, distancePerSconed).SetEase(ease).SetSpeedBased()
            .OnComplete(MoveComplete);
    }

    /// <summary>
    /// 设置坐标位置
    /// </summary>
    /// <param name="pos"></param>
    public void SetPos(Vector2 pos)
    {
        playerPos = pos;
    }

    private void MoveComplete()
    {
        SetPos(destination);
        GridData gridData = LevelManager.Instance.GetGridData((int) playerPos.x, (int) playerPos.y);
        if (gridData.GridType == EGridType.Wall && gridData.GridDirection != EDirection.None)
        {
            triggerMove = true;
            switch (gridData.GridDirection)
            {
                case EDirection.Left:
                case EDirection.Right:
                case EDirection.Up:
                case EDirection.Down:
                case EDirection.LeftRight:
                case EDirection.UpDown:
                    break;
                case EDirection.LeftUp:
                    if (moveDirection == EDirection.Right)
                        moveDirection = EDirection.Up;
                    if (moveDirection == EDirection.Down)
                        moveDirection = EDirection.Left;
                    break;
                case EDirection.UpRight:
                    if (moveDirection == EDirection.Left)
                        moveDirection = EDirection.Up;
                    if (moveDirection == EDirection.Down)
                        moveDirection = EDirection.Right;
                    break;
                case EDirection.RightDown:
                    if (moveDirection == EDirection.Left)
                        moveDirection = EDirection.Down;
                    if (moveDirection == EDirection.Up)
                        moveDirection = EDirection.Right;
                    break;
                case EDirection.DownLeft:
                    if (moveDirection == EDirection.Right)
                        moveDirection = EDirection.Down;
                    if (moveDirection == EDirection.Up)
                        moveDirection = EDirection.Left;
                    break;
            }
        }
        else
        {
            moveDirection = EDirection.None;
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        GridItem gridItem = other.GetComponent<GridItem>();
        if (gridItem == null)
        {
            Debug.Log("Trigger grid is null!");
            return;
        }

        switch (gridItem.GetGridData.GridType)
        {
            case EGridType.Target:
                if (!gridItem.GetGridData.IsTargetFinish)
                {
                    gridItem.GetGridData.IsTargetFinish = true;
                    hasGetTargetCnt++;
                    gridItem.TargetShowLogic();
                    LevelManager.Instance.startOrEndGridItem.StartOrEndShowLogic();
                    GameManager.Instance.PlayTargetClip();
                    Debug.LogWarning($"当前条件{hasGetTargetCnt}/{LevelManager.Instance.LevelTargetCnt}");
                }

                break;
            case EGridType.StartOrEnd:
                if (IsFinishCondition && !IsPassLevel)
                {
                    IsPassLevel = true;
                    Debug.LogWarning("恭喜你！通关了！！！");
                    GameManager.Instance.SaveData(LevelManager.Instance.CurLevel, ELevelStatus.Pass);
                    UIViewManager.Instance.OpenUIView(EUIViewID.VictoryView);
                }

                break;
            case EGridType.SwitchBtn:
                if (gridItem.GetGridData.IsBtnCanUse)
                {
                    gridItem.TriggerSwitchLogic();
                    GameManager.Instance.PlaySwitchBtnSound();
                }

                break;
        }
    }
}